/*
 * @Author: 星孑
 * @Date: 2022-03-10 15:24:22
 * @LastEditors: 星孑
 * @LastEditTime: 2022-04-12 16:21:17
 * @FilePath: /vue-template-web/src/permission.js
 * @Description: 路由导航，权限管理
 */
import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // getToken from cookie

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['login'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  NProgress.start() // start progress bar
  if (getToken()) {
    if (to.name === 'login') {
      next({ path: '/' })
      NProgress.done() // if current page is dashboard will not trigger	afterEach hook, so manually handle it
    } else {
      if (store.getters.userInfo.id) {
        next()
      } else {
        const data = await store.dispatch('GetUserInfo')
        const accessedRouters = await store.dispatch(
          'GenerateRoutes',
          data.permissionRespList || []
        )
        accessedRouters.forEach(route => {
          router.addRoute(route)
        })

        // 如果在defaultRoutes里面添加，会导致刷新页面时候直接重定向到502
        router.addRoute(
          {
            path: '*',
            hidden: true,
            redirect: '/502'
          })
        setTimeout(() => {
          console.log('-------', 't0', router)
        }, 1000)
        next({ ...to, replace: true })
      }
    }
  } else {
    if (whiteList.includes(to.name)) {
      next()
    } else {
      next({ name: 'login' })
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done() // finish progress bar
})
